<?php

namespace plugin\cms\app\bll;

use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use plugin\cms\app\validate\Tag as ValidateTag;
use support\Db;

/**
 * 标签
 */
class Tag
{
    /**
     * 查找标签
     *
     * @param integer $siteid
     * @return array
     */
    public function select(int $siteid): array
    {
        return  Db::table('cms_tag')
            ->where('siteid', '=', $siteid)
            ->get()
            ->map(function ($value) {
                return (array)$value;
            })
            ->toArray();
    }

    /**
     * 查找某个标签
     *
     * @param integer $id
     * @param integer $siteid
     * @return array
     */
    public function find(int $id, int $siteid): array
    {
        $tag = Db::table('cms_tag')
            ->where('id', '=', $id)
            ->where('siteid', '=', $siteid)
            ->first();
        return $tag === null ? [] : get_object_vars($tag);
    }

    /**
     * 添加标签
     *
     * @param array $data
     * @return integer
     */
    public function add(array $data): int
    {
        $ValidateTag = new ValidateTag();
        if (!$ValidateTag->check($data)) {
            throw new Exception($ValidateTag->getSimpleError());
        }
        return Db::table('cms_tag')->insertGetId($data);
    }


    /**
     * 编辑
     *
     * @param integer $id
     * @param integer $siteid
     * @param array $data
     * @return integer
     */
    public function edit(int $id, int $siteid, array $data): int
    {
        $data['siteid'] = $siteid;
        $ValidateTag = new ValidateTag();
        if (!$ValidateTag->check($data)) {
            throw new Exception($ValidateTag->getSimpleError());
        }
        return  Db::table('cms_tag')
            ->where('id', '=', $id)
            ->where('siteid', '=', $siteid)
            ->update($data);
    }

    /**
     * 删除标签
     *
     * @param integer $id
     * @param integer $siteid
     * @return integer
     */
    public function delete(int $id, int $siteid): int
    {
        return  Db::table('cms_tag')
            ->where('id', '=', $id)
            ->where('siteid', '=', $siteid)
            ->delete();
    }



    /**
     * 分页查询
     *
     * @param integer $pagesize
     * @return LengthAwarePaginator
     */
    public function paginate(int $siteid, int $pagesize = 20): LengthAwarePaginator
    {
        return  Db::table('cms_tag')
            ->where('siteid', '=', $siteid)
            ->orderBy('id', 'desc')
            ->paginate($pagesize);
    }
}
